#include "vtor_spi.h"

#ifdef __VTOR_SPI__

/*
VtorSpi只需要考虑cpol即可，设置为clk空闲电平
CPOL = 1：表示空闲时是高电平，
------|__--__--第一个跳变沿为下降沿

CPOL = 0：表示空闲时是低电平，
______|--__--__第一个跳变沿为上升沿

VtorSpi做了兼容，不需要考虑cpha
CPHA = 0：表示从第一个跳变沿开始采样
______|--__--__

CPHA = 1：表示从第二个跳变沿开始采样
______--|__--__
*/

void VtorSpi_SetClkBusy(VtorSpi* spi)
{
	if (VTOR_SPI_POLARITY_LOW == spi->cpol)
	{
		VtorSpi_WriteClk(spi, GPIO_LEVEL_HIGH);
	}
	else
	{
		VtorSpi_WriteClk(spi, GPIO_LEVEL_LOW);
	}

}
void VtorSpi_SetClkIdle(VtorSpi* spi)
{
	if (VTOR_SPI_POLARITY_LOW == spi->cpol)
	{
		VtorSpi_WriteClk(spi, GPIO_LEVEL_LOW);
	}
	else
	{
		VtorSpi_WriteClk(spi, GPIO_LEVEL_HIGH);
	}
}

// o h i l
// h o l i
// o l i h
// l o h i
// https://www.cnblogs.com/gmpy/p/12461461.html
// https://blog.csdn.net/baidu_39594043/article/details/120362744
void VtorSpi_WriteRead(VtorSpi* spi, uint8_t* txBuf, uint8_t* rxBuf, uint16_t len)
{
	uint8_t cnt;
	uint16_t i;

	VtorSpi_WriteCs(spi, GPIO_LEVEL_LOW);
	for(i = 0; i < len; i++)
	{
		uint8_t txByte = 0x55;
		uint8_t rxByte = 0xaa;
		if (NULL != txBuf)
		{
			txByte = *txBuf;
			txBuf++;
		}
		for(cnt=0;cnt<8;cnt++)
		{
			VtorSpi_WriteMosi(spi, txByte & 0x80);
			txByte <<= 1;

			VtorSpi_Delay(1);
			VtorSpi_SetClkBusy(spi);
			VtorSpi_Delay(1);
			VtorSpi_SetClkIdle(spi);
			VtorSpi_Delay(1);

			rxByte<<=1;
			if(VtorSpi_ReadMiso(spi))
			{
				rxByte |= 0x01;
			}
		}
		if (NULL != rxBuf)
		{
			*rxBuf = rxByte;
			rxBuf++;
		}
	}
	VtorSpi_WriteCs(spi, GPIO_LEVEL_HIGH);
}


#endif // __VTOR_SPI__
